;
(function() {
	var midEvent = require("./index");
	var emailSender = require("../core/_include/email");
	var notify = require("../server/RESTAPI/notify");
	var fs = require("fs");
	var mail_ach_need_shipment_content = fs.readFileSync(__dirname + "/mail.ach.need.shipment.html").toString();
	var mail_ach_need_receiving_content = fs.readFileSync(__dirname + "/mail.ach.need.receiving.html").toString();
	//通知商家发货
	midEvent.on("ach.need.shipment", function(ach_id) {
		var ach = midEvent.Class.Ach.get(ach_id);
		var user = midEvent.Class.User.get(ach.info.user_id);
		var bus = midEvent.Class.Bus.get(ach.info.bus_id);
		if (!bus.config.is_close_email_notify) {
			var replyContent = {
				to: bus.info.email,
				title: "【点纳微站】您收到一个新的订单，编号为：" + ach_id,
				content: mail_ach_need_shipment_content.format({
					ach_id: ach._id,
					ach_user: user.info.name,
					ach_cash: "￥" + (ach.cus_cash || ach.cash).toFixed(2),
					ach_time: (new Date(ach.create_time)).format("yyyy-MM-dd HH:mm:ss"),
					ach_goods_info: ach.info.goods_info.map(function(goods_info) {
						return goods_info.goods.goods_name + "(*" + goods_info.num + goods_info.goods.unit + ")<br/>";
					}),
					ach_address_info: (function() {
						var address_info = ach.info.user_address;
						if (!address_info) { //虚拟商品没有收获地址，所以
							return "（此订单包含虚拟商品，无需实际收获地址）";
						}
						var res = address_info.name + "，";
						if (address_info.mobilenumber) {
							res += address_info.mobilenumber + (address_info.phonenumber ? "/" + address_info.phonenumber : "")
						} else {
							res += address_info.phonenumber
						}
						res += "，" + address_info.town + "，" + address_info.county + "，" + address_info.detail
						return res;
					}()),
				})
			};
			console.log("发送邮件到商家：", bus.info.email);
			emailSender(replyContent, function(error) {
				if (error) {
					console.error("新的订单提示邮件 发送失败", replyContent, error);
				} else {
					console.log("新的订单提示邮件 已经发送");
				}
			});
		}
	});
	//通知用户收货
	midEvent.on("ach.need.receiving", function(ach_id) {
		var ach = midEvent.Class.Ach.get(ach_id);
		var user = midEvent.Class.User.get(ach.info.user_id);
		var bus = midEvent.Class.Bus.get(ach.info.bus_id);
		if (user.info.email) {
			console.log("发送邮件到用户：", user.info.email);
			var replyContent = {
				to: user.info.email,
				title: "【点纳微站】您有一份订单已经发货，编号为：" + ach_id,
				content: mail_ach_need_receiving_content.format({
					bus_url: bus.getOneVisitableUrl(),
					bus_title: bus.info.title,
					ach_id: ach._id,
					ach_cash: "￥" + (ach.cus_cash || ach.cash).toFixed(2),
					ach_time: (new Date(ach.create_time)).format("yyyy-MM-dd HH:mm:ss"),
					ach_goods_info: ach.info.goods_info.map(function(goods_info) {
						return goods_info.goods.goods_name + "(*" + goods_info.num + goods_info.goods.unit + ")<br/>";
					}),
					ach_address_info: (function() {
						var address_info = ach.info.user_address;
						var res = address_info.name + "，";
						if (address_info.mobilenumber) {
							res += address_info.mobilenumber + (address_info.phonenumber ? "/" + address_info.phonenumber : "")
						} else {
							res += address_info.phonenumber
						}
						res += "，" + address_info.town + "，" + address_info.county + "，" + address_info.detail
						return res;
					}()),
				})
			};
			emailSender(replyContent, function(error) {
				if (error) {
					console.error("订单发货提示邮件 发送失败", replyContent, error);
				} else {
					console.log("订单发货提示邮件 已经发送");
				}
			});
		} else {
			console.log("用户未配置邮箱");
		}
	});
	midEvent.on("ach.cancel", function(ach_id, user_id, bus_id) {
		var role = midEvent.Tool.role;
		var bus_sockSet = role.getBusSockSet(bus_id);
		notify.send(bus_sockSet, "ach.cancel", ach_id);
	});
	midEvent.on("ach.before_cancel", function(ach_id, user_id, bus_id) {
		/*控制空间（餐桌）*/
		var ach = midEvent.Class.Ach.get(ach_id);
		if (ach.info.use_space) {
			var bus = midEvent.Class.Bus.get(bus_id);
			var space = midEvent.Class.BusSpace.get(ach.info.space._id);
			space.use_state = midEvent.Class.BusSpace.USE_STATE.可用;
			bus.updateSpace(space._id, space)
		}
	});
	midEvent.on("ach.new", function(ach_id, user_id, bus_id) {
		var role = midEvent.Tool.role;
		var bus_sockSet = role.getBusSockSet(bus_id);
		var ach = midEvent.Class.Ach.get(ach_id);
		notify.send(bus_sockSet, "ach.new", ach.getDetail());
		/*控制空间（餐桌）*/
		if (ach.info.use_space) {
			var bus = midEvent.Class.Bus.get(ach.info.bus_id);
			var space = midEvent.Class.BusSpace.get(ach.info.space._id);
			space.use_state = midEvent.Class.BusSpace.USE_STATE.正在使用;
			bus.updateSpace(space._id, space);
		}
	});
	midEvent.on("ach.state.changed", function(ach_id, user_id, bus_id, state) {
		var role = midEvent.Tool.role;
		//发送给用户
		var user_sockSet = role.getUserSockSet(user_id);
		notify.send(user_sockSet, "ach.state.changed", {
			ach_id: ach_id,
			state: state
		});
		//发送给商家
		var bus_sockSet = role.getBusSockSet(bus_id);
		notify.send(bus_sockSet, "ach.state.changed", {
			ach_id: ach_id,
			state: state
		});
	});
	midEvent.on("ach.deal.end", function(ach_id) {
		var ach = midEvent.Class.Ach.get(ach_id);
		/*控制空间（餐桌）*/
		if (ach.info.use_space) {
			console.log("餐桌使用完毕，设置为可用");
			var bus = midEvent.Class.Bus.get(ach.info.bus_id);
			if (ach.info.space && ach.info.space._id) {
				var space = midEvent.Class.BusSpace.get(ach.info.space._id);
				space.use_state = midEvent.Class.BusSpace.USE_STATE.可用;
				bus.updateSpace(space._id, space)
			}
		}
	})
	midEvent.on("ach.online_pay_success", function(pay_ach_id) {
		var pay_ach = midEvent.Class.Pay_ach.get(pay_ach_id);
		var ach = midEvent.Class.Ach.get(pay_ach.ach_id);
		try {
			var role = midEvent.Tool.role;
			//发送给订单拥有者，而不是支付者
			var user_sockSet = role.getUserSockSet(ach.info.user_id);
			notify.send(user_sockSet, "pay_success", pay_ach.getAchDetail());
		} catch (e) {
			console.error(e)
		}
	});
	midEvent.on("ach.pay_end.call_back_url.success", function(ach_id, user_id) {
		console.log(arguments);
		var role = midEvent.Tool.role;
		var user_sockSet = role.getUserSockSet(user_id);
		notify.send(user_sockSet, "ach.pay_end.call_back_url.success", {
			ach_id: ach_id
		});
	});
	midEvent.on("ach.pay_end.call_back_url.error", function(ach_id, user_id) {
		var role = midEvent.Tool.role;
		var user_sockSet = role.getUserSockSet(user_id);
		notify.send(user_sockSet, "ach.pay_end.call_back_url.error", {
			ach_id: ach_id
		});
	});
}());